package net.qiyuesuo.utils;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Http请求处理工具
 * @author Administrator
 *
 */
public class HttpUtils {
	
	private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
	/**
	 * 获取相应内容
	 * @param conn 与服务器连接
	 * @return 响应内容
	 */
	public static String getResponse (HttpURLConnection conn, String requestMethod) {
		StringBuffer msg = new StringBuffer();
		try {
			conn.setDoOutput(true);
			conn.setDoInput(true);
			
			conn.setInstanceFollowRedirects(true);
			conn.setConnectTimeout(3000);
			if(requestMethod.equals("GET")) {
				conn.setRequestMethod("GET");
				conn.setUseCaches(true);
			}else {
				conn.setRequestMethod("POST");
				conn.setUseCaches(false);
			}
			//连接
			conn.connect();
			int code = conn.getResponseCode();
			if(code == 200) {
				//正常相应 获取输出流
				try(InputStream input = conn.getInputStream()){
					int len = 0;
					byte[] buf = new byte[1024];
					while((len = input.read(buf))!= -1) {
						msg = msg.append(new String(buf,0,len));
					}
				}
				conn.disconnect();
			}else {
				logger.error("获取服务器相应失败！");
			}
		} catch ( IOException e) {
			logger.error("连接服务器失败！");
		}
		return msg.toString();
	}
	
	/**
	 * 
	 * 向服务器发送上传文件请求
	 * @param url
	 * @param filePath
	 * @param fileName
	 * @return 响应结果
	 */
	public static String upload(String strUrl ,String filePath ,String fileName) {
		String BOUNDARY = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
		String PREFIX = ("--"+BOUNDARY);
		StringBuffer msg = new StringBuffer();
		HttpURLConnection  conn = null;
		try {
			URL url = new URL(strUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(3000);
		} catch ( IOException e) {
			e.printStackTrace();
		}
		//配置请求头
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setRequestProperty("Content-Type", " multipart/form-data; boundary=" + BOUNDARY);
		conn.setRequestProperty("Accept", "*/*");
		//获取输入流
		Path path = Paths.get(filePath);
		try(OutputStream out = new DataOutputStream(conn.getOutputStream());
				FileInputStream input = new FileInputStream(path.toFile());
				){
			//将要上传的数据
			StringBuffer strBuf = new StringBuffer();
			// 标识payLoad + 文件流的起始位置
			strBuf.append(PREFIX+"\r\n");
			strBuf.append("content-disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n");
			strBuf.append("content-type: text/plain"  + "\r\n\r\n");
			out.write(strBuf.toString().getBytes());
			//获取文件流
			int len = 0;
			byte[] buf = new byte[1024];
			while((len = input.read(buf))!= -1) {
				out.write(buf, 0, len);
			}
			out.write(("\r\n"+PREFIX+"--\r\n").getBytes());
			//获取返回数据
			int code = conn.getResponseCode();
			if(code == 200) {
				// 正常相应 获取输出流
				try (InputStream in = conn.getInputStream()) {
					int serverLen = 0;
					byte[] serverBuf = new byte[1024];
					while ((serverLen = in.read(serverBuf)) != -1) {
						msg.append(new String(serverBuf,0,serverLen));
					}
				}
				conn.disconnect();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg.toString();
	}
	
	
}
